package com.buddy.learn.javasource._thread;

import java.util.concurrent.Semaphore;


/**
 * @author Buddy
 * @date 2021/4/18
 */
public class PrintABCUseSemaphore {

    private int times;
    private Semaphore semaphoreA = new Semaphore(1);
    private Semaphore semaphoreB = new Semaphore(0);
    private Semaphore semaphoreC = new Semaphore(0);

    public PrintABCUseSemaphore(int times) {
        this.times = times;
    }

    public void printA(){
        try {
            print("A",semaphoreA,semaphoreB);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void printB(){
        try {
            print("B",semaphoreB,semaphoreC);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void printC(){
        try {
            print("C",semaphoreC,semaphoreA);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void print(String value, Semaphore current, Semaphore next) throws InterruptedException {
        for (int i=0;i<times;i++){
            // 从此信号量获取一个许可，在提供一个许可前一直将线程阻塞，否则线程被中断。
            current.acquire();
            System.out.println(i+":"+value);
            // 释放一个许可，将其返回给信号量。
            next.release();
        }
    }


}
